<?php
namespace app\admin\controller;
use think\Controller;
use catetree\Catetree;
use app\admin\validate\CateValidate;
/**
 * 文章分类
 */
class Cate extends Controller
{
	//列表页
	public function lists(){
		$cateObj=db('cate');
		
		$cate=new Catetree();
		if (request()->isPost()) {
			$data=input('post.');
			$cate->cateSort($data['sort'],$cateObj);
			
			$this->success('排序成功','lists');
			
		}
		$cateRes=$cateObj->order('sort desc')->select();
		$cateRes=$cate->catetree($cateRes);
		$this->assign('cateRes',$cateRes);
		return view();
	}
	// 添加
	public function add(){
		$cateObj=db('cate');
		$cateRes=new Catetree();
		if (request()->isPost()) {
			$data=input('post.');
			// 判断是否可以添加子栏目
			if(in_array($data['pid'], ['1','3'])){
				$this->error('系统分类不能作为上级栏目');
			}
			//
			if($data['pid']==2){
				$data['cate_type']=3;
			}
			//
			$cates=db('cate')->field('pid')->find($data['pid']);
			$cateId=$cates['pid'];
			if ($cateId==2) {
				$this->error('此分类不能作为上级分类');
			}
			//验证
			$validate =new CateValidate();
			if(!$validate->check($data)){
    			$this->error($validate->getError());
			}
			$add=db('cate')->insert($data);
			if($add){
				$this->success('分类添加成功','cate/lists');
			}else{
				$this->error('分类添加失败');
			}
			return;
		}
		$cate=$cateObj->order('sort desc')->select();
		$cate=$cateRes->catetree($cate);
		$this->assign('cate',$cate);
		return view();
	}
	// 编辑
	public function edit(){
		$cateObj=db('cate');
		$cateRes=new Catetree();
		if (request()->isPost()) {
			$data=input('post.');
			//验证
			$validate =new CateValidate();
			if(!$validate->check($data)){
    			$this->error($validate->getError());
			}
			$save=$cateObj->update($data);
			if($save!==false){
				$this->success('分类编辑成功','cate/lists');
			}else{
				$this->error('分类编辑失败');
			}
			return;
		}
		$cate=$cateObj->order('sort desc')->select();
		$cate=$cateRes->catetree($cate);
		$db=db('cate')->where('id',input('id'))->find();
		$this->assign(array(
			'cate'=>$cate,
			'db'=>$db,
		));
		return view();
	}
	// 删除
	public function del($id){
		$cateTree=new Catetree();
		$cate=db('cate');
		$sonids=$cateTree->childrenids($id,$cate);
		$sonids[]=intval($id);//当前栏目id
		$arr=[1,2,3];
		$arrRes=array_intersect($arr, $sonids);//取交集
		if ($arrRes) {
			$this->error('系统内置分类不能删除');
		}
		// halt($sonids);
		// 删除之前判断分类文章及相关缩略图的删除
		$article=db('article');
		foreach ($sonids as $k => $v) {
			$artRes=$article->field('id,thumb')->where(array('cate_id'=>$v))->select();
			foreach ($artRes as $k1=> $v1) {
				$picSrc=IMG_UPLOADS.$v1['thumb'];
				if (file_exists($picSrc)) {
					@unlink($picSrc);
				}
				$article->delete($v1['id']);
			}
		}
		$del=$cate->delete($sonids);
		if($del){
				$this->success('分类删除成功','lists');
			}else{
				$this->error('分类删除失败');
		}
	}
	
}
